package com.wsd.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
  *    手写httpServer   第一步
 * @author fengmoboy
 *
 */
public class Step1Server {
	
	public static void main(String[] args) throws IOException {
		ServerSocket socketServer = new ServerSocket(8000);
		
		// Main Thread
		while(true) {
			// Blocking...
			Socket socket = socketServer.accept();
			System.out.println("A socket created");
			
			DataInputStream iptStream = new DataInputStream(socket.getInputStream());
			BufferedReader bfReader = new BufferedReader(new InputStreamReader(iptStream));
			
			StringBuilder requestBuilder = new StringBuilder();
			
			String line = "";
			while(!(line = bfReader.readLine()).isEmpty()) {
				requestBuilder.append(line+"\n");
			}
			String request = requestBuilder.toString();
			System.out.println(request);
			BufferedWriter bfWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			bfWriter.write("HTTP/1.1 200 ok\n\nHello World!\n");
			bfWriter.flush();
			socket.close();
		}
	}
}
